
/**
 *	TrueMusic - simple java mp3 player
 *
 *	TrueMusic is free software; you can redistribute it
 *	and/or modify it under the terms of the GNU General
 *	Public License as published by the Free Software
 *	Foundation; either version 2 of the License or (at
 *	your option) any later version.
 *	
 *	This program is distributed in the hope that it will be
 *	useful but WITHOUT ANY WARRANTY; without even the 
 *	implied warranty of the MERCHANTABILITY or FITNESS FOR
 *	A PARTICULAR PURPOSE. See the GNU General Public
 *	License for more details.
 *	
 *	Copyright (c)2005-2006 Ryan Macnak <ambiguousprep@gmail.com>
 */

package com.servequake.truemusic;


import javazoom.jl.player.advanced.AdvancedPlayer;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.File;

// supports WAV for sure and possibly RIFF?
public class GenericAudioFile extends AudioFile
{
	public void dispose()
	{
		p=null;
		prog=null;
		interrupt();
	}

	GoodPlayer p;

	File file;
	int frames = 0;

	JSlider prog;


	GenericAudioFile(File f, JSlider prog) throws Exception
	{
		this.file = f;

		p = new GoodPlayer( f.toString() ) ;

		this.frames = p.max;
		this.prog = prog;

		start();
	}


	public String filename()
	{
		return file.toString();
	}

	private volatile boolean pause = true;
	private volatile Integer pos = 0;

	public String getTitle()
	{
		return file.toString();
	}

	public String getArtist()
	{
		return "";
	}

	public String getAlbum()
	{
		return "";
	}

	public int getFrames()
	{
		return frames;
	}


	public String toString()
	{
		return file.toString();
	}

	public synchronized void play()
	{
		if(!pause) pos = 0;
		else
		{
			pause = false;
			notify();
		}
	}

	public synchronized void pause()
	{
		pause = !pause;
		if( !pause ) notify();
	}

	public synchronized void setPos(int npos)
	{	
		this.pos = npos;
	}

	public synchronized void stop2()
	{
		pos = 0;
		pause = true;
	}

	public void run()
	{
		while(true)
		{
		try
		{
			
			if(pause)
			{ 
				//prog.setValue(pos);

				synchronized(this)
			 	{
                   			while(pause) wait();
           			}
			}

			synchronized(pos)
			{
				if(p == null) p = new GoodPlayer(file.toString());

				javazoom.jl.player.JavaSoundAudioDevice.vol.setValue( TrueMusic.inst.cp.volume.getValue() );

				boolean more = p.play(pos);
				if(more) pos++;
				else 
				{
					pos = 0; pause = true; TrueMusic.inst.cp.next();
				}
				prog.setValue(pos);
			}

			//System.out.println(pos);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			if(p==null)return;
		}
		}
	}
}
